#!/usr/bin/env python
# -*- coding: utf-8 -*-

import tornado
import tornado.web
import datetime
from utils import log
import json
from config import etc
from controls import data_city_base_mysql
from controls import data_city_map_mysql
from controls import data_sight_img_mysql
from controls import data_product_desc_mongo
from controls import data_card_info_mongo
from config import conf
import tcelery
from utils import file_util
from utils.session_mc import BaseHandler
from tasks.cms import update_all

'''
仅供后台使用，给城市更新地图
path : citymapupdate
'''
class CityMapUpdateHandler(tornado.web.RequestHandler) :

    def get(self) :
        all_city = data_city_base_mysql.get_city_all_by_bg();
        city_sel = '选择城市<select onchange="" name="cityid">'
        for item in all_city :
            city_sel += '<option value="' + str(item['cityid']) + '">' + str(item['cname'])+ '</option>'
        city_sel += '</select><br /><br/>'

        self.write('''
                <html>
                <head><title>Upload City Map</title></head>
                <body>
                <form action='citymapupdate' enctype="multipart/form-data" method='post'>
                ''' 
                + city_sel +
                '''
                地图csb文件<input type='file' name='csbfile'/><br/>
                地图jpg文件<input type='file' name='jpgfile'/><br/>
                地图png文件<input type='file' name='pngfile'/><br/>
                地图plist文件<input type='file' name='plistfile'/><br/>
                城市小球icon文件<input type='file' name='iconfile'/><br/>
                景点信息JSON文件<input type='file' name='jsonfile'/><br/><br/>
                <input type='submit' value='submit'/>
                </form>
                </body>
                </html>
            ''')


    def post(self) :
        try :
            # check
            '''
            remoteip = self.request.headers['X-Real-Ip']
            if remoteid != etc.yunweiip :
                log.w(remoteid + ' try to access /citymapupdate.')
                res = { 'idx':0, 'ret':1, 'msg':'error.', 'res':[] }
                self.write( json.dumps(res) )
                self.finish()
                return
            '''

            csbfile = None
            jpgfile = None
            pngfile = None
            plistfile = None
            iconfile = None
            jsonfile = None
            try :
                csbfile = self.request.files['csbfile'][0]
            except Exception as e :
                print 'csbfile do not upload...'
            try :
                jpgfile = self.request.files['jpgfile'][0]
            except Exception as e :
                print 'jpgfile do not upload...'
            try :
                pngfile = self.request.files['pngfile'][0]
            except Exception as e :
                print 'pngfile do not upload...'
            try :
                plistfile = self.request.files['plistfile'][0]
            except Exception as e :
                print 'plistfile do not upload...'
            try :
                iconfile = self.request.files['iconfile'][0]
            except Exception as e :
                print 'iconfile do not upload...'
            try :
                jsonfile = self.request.files['jsonfile'][0]
            except Exception as e :
                print 'jsonfile do not upload...'
        
            cityid = self.get_argument( 'cityid' )
        
            if not cityid :
                log.w('params fetching error')
                res = { 'idx':0, 'ret':2, 'msg':'ng', 'res':[] }
                self.write( json.dumps(res) )
                self.finish()
                return
            
            '''fdfs.upload_file's result
                res = {
                    'imgid' : 0 ,
                    'group' : res_group ,
                    'path' : res_file_id.split('.',1)[0] ,
                    'ext' : p_ext_name ,
                    'file_id' : res_file_id ,
                }
            '''
        
            csbfile_res = None if not csbfile else file_util.map_file_upload(csbfile, cityid)
            jpgfile_res = None if not jpgfile else file_util.map_file_upload(jpgfile, cityid)
            pngfile_res = None if not pngfile else file_util.map_file_upload(pngfile, cityid)
            plistfile_res = None if not plistfile else file_util.map_file_upload(plistfile, cityid)
            iconfile_res = None if not iconfile else file_util.map_file_upload(iconfile, cityid)
            jsonfile_res = None if not jsonfile else file_util.map_file_upload(jsonfile, cityid)
            
            error = False
            res = { 'idx':0, 'ret':1, 'msg':'ng', 'res':[] }
            if csbfile and not csbfile_res:
                error = True
                res['res'].append('csbfile upload failure.')
            if jpgfile and not jpgfile_res:
                error = True
                res['res'].append('jpgfile upload failure.')
            if pngfile and not pngfile_res:
                error = True
                res['res'].append('pngfile upload failure.')
            if plistfile and not plistfile_res:
                error = True
                res['res'].append('plistfile upload failure.')
            if iconfile and not iconfile_res:
                error = True
                res['res'].append('iconfile upload failure.')
            if jsonfile and not jsonfile_res:
                error = True
                res['res'].append('jsonfile upload failure.')

            if error :
                log.e(res)
                self.write( json.dumps(res) )
                self.finish()
                return
        
            city_map_dict = data_city_map_mysql.get_city_map_by_cityid( int (cityid) )
            log.i(city_map_dict)
            
            map_item = {}
            version = 1;
            if city_map_dict:
                map_item = city_map_dict
                del map_item['id']
                version += map_item['version']
        
            map_item['cityid'] = int (cityid)
            map_item['version'] = version
            map_item['ctime'] = datetime.datetime.now()
            
            if csbfile_res :
                map_item['csbfile'] = 'http://static.shitouren.com/group'+str(csbfile_res['group'])+'/'+csbfile_res['path']+'.'+csbfile_res['ext']
            if jpgfile_res :
                map_item['jpgfile'] = 'http://static.shitouren.com/group'+str(jpgfile_res['group'])+'/'+jpgfile_res['path']+'.'+jpgfile_res['ext']
            if pngfile_res :
                map_item['pngfile'] = 'http://static.shitouren.com/group'+str(pngfile_res['group'])+'/'+pngfile_res['path']+'.'+pngfile_res['ext']
            if plistfile_res :
                map_item['plistfile'] = 'http://static.shitouren.com/group'+str(plistfile_res['group'])+'/'+plistfile_res['path']+'.'+plistfile_res['ext']
            if iconfile_res :
                map_item['iconfile'] = 'http://static.shitouren.com/group'+str(iconfile_res['group'])+'/'+iconfile_res['path']+'.'+iconfile_res['ext']
            if jsonfile_res :
                map_item['jsonfile'] = 'http://static.shitouren.com/group'+str(jsonfile_res['group'])+'/'+jsonfile_res['path']+'.'+jsonfile_res['ext']
        
            log.i(map_item)
        
            update_res = data_city_map_mysql.add_city_map_item( map_item )
            if not update_res :
                res['res'].append('add city map error. cityid:' + cityid)
                log.e(res)
                self.write( json.dumps(res) )
                self.finish()
                return
        
            update_res = data_city_base_mysql.update_city_version_by_cityid( int(cityid), p_version=version )
            if not update_res :
                res['res'].append('update city_base version error. cityid:' + cityid)
                log.e(res)
                self.write( json.dumps(res) )
                self.finish()
                return
        except Exception as e :
            log.exp(e)
            res = { 'idx':0, 'ret':1, 'msg':'ng', 'res':[] }
            self.write( json.dumps(res) )
            self.finish()
            return
 
        return self.redirect( r"/citymapupdate" )

'''
仅供后台使用，更新城市所有特产信息Json文件
path : cityproductupdate
'''
class ProductUpdateHandler(tornado.web.RequestHandler) :

    def get(self) :
        all_city = data_city_base_mysql.get_city_all_by_bg();
        city_sel = '选择城市<select onchange="" name="cityid">'
        for item in all_city :
            city_sel += '<option value="' + str(item['cityid']) + '">' + str(item['cname'])+ '</option>'
        city_sel += '</select><br /><br/>'
        
        self.write('''
                <html>
                <head><title>Upload City Product Json</title></head>
                <body>
                <form action='cityproductupdate' enctype="multipart/form-data" method='post'>
                ''' 
                + city_sel +
                '''
                该城市所有特产信息的JSON文件<input type='file' name='jsonfile'/><br/>(注意：文件内容编码格式为utf-8)<br/>
                <input type='submit' value='submit'/>
                </form>
                </body>
                </html>
            ''')

    def post(self) :
        try :
            # check
            '''
            remoteip = self.request.headers['X-Real-Ip']
            if remoteid != etc.yunweiip :
                log.w(remoteid + ' try to access /cityproductupdate.')
                res = { 'idx':0, 'ret':1, 'msg':'error.', 'res':[] }
                self.write( json.dumps(res) )
                self.finish()
                return
            '''

            jsonfile = None
            try :
                jsonfile = self.request.files['jsonfile'][0]
            except Exception as e :
                print 'jsonfile need upload...'
            cityid = int (self.get_argument( 'cityid' ) )
        
            if not ( cityid and jsonfile ):
                log.w('params fetching error')
                res = { 'idx':0, 'ret':1, 'msg':'Json文件没有上传', 'res':[] }
                self.write( json.dumps(res) )
                self.finish()
                return
            
            # 把文件内容读入，存入到mongodb
            #exec("json_dict="+jsonfile['body'])
            json_dict = json.loads(jsonfile['body'])
            
            res = { 'idx':0, 'ret':1, 'msg':'ng', 'res':[] }
            if cityid != json_dict['cityid']:
                res['res'].append('this json file content dont match selected cityid.')
                self.write( json.dumps(res) )
                self.finish()
                return
        
            # update to mongodb
            data_product_desc_mongo.update_city_product( cityid, json_dict['products'] )
            
            res['msg'] = "update city's products success. cityid:" + str(cityid)
            res['ret'] = 0
            self.write( json.dumps(res) )
            self.finish()
            return
        except Exception as e :
            log.exp(e)
            res = { 'idx':0, 'ret':1, 'msg':'ng', 'res':[] }
            self.write( json.dumps(res) )
            self.finish()
            return
 
        return self.redirect( r"/cityproductupdate" )

'''
仅供后台使用，更新城市所有卡牌信息Json文件
path : citycardupdate
'''
class CardUpdateHandler(tornado.web.RequestHandler) :

    def get(self) :
        all_city = data_city_base_mysql.get_city_all_by_bg();
        city_sel = '选择城市<select onchange="" name="cityid">'
        for item in all_city :
            city_sel += '<option value="' + str(item['cityid']) + '">' + str(item['cname'])+ '</option>'
        city_sel += '</select><br /><br/>'
        
        self.write('''
                <html>
                <head><title>Upload City Card Json</title></head>
                <body>
                <form action='citycardupdate' enctype="multipart/form-data" method='post'>
                ''' 
                + city_sel +
                '''
                该城市所有卡牌信息的JSON文件<input type='file' name='jsonfile'/><br/>(注意：文件内容编码格式为utf-8)<br/>
                <input type='submit' value='submit'/>
                </form>
                </body>
                </html>
            ''')

    def post(self) :
        try :
            # check
            '''
            remoteip = self.request.headers['X-Real-Ip']
            if remoteid != etc.yunweiip :
                log.w(remoteid + ' try to access /citycardupdate.')
                res = { 'idx':0, 'ret':1, 'msg':'error.', 'res':[] }
                self.write( json.dumps(res) )
                self.finish()
                return
            '''
            
            jsonfile = None
            try :
                jsonfile = self.request.files['jsonfile'][0]
            except Exception as e :
                print 'jsonfile need upload...'
            cityid = int (self.get_argument( 'cityid' ) )
        
            if not ( cityid and jsonfile ):
                log.w('params fetching error')
                res = { 'idx':0, 'ret':1, 'msg':'please input this city\'s cards Json file.', 'res':[] }
                self.write( json.dumps(res) )
                self.finish()
                return
            
            # 把文件内容读入，存入到mongodb
            #exec("json_dict="+jsonfile['body'])
            json_dict = json.loads(jsonfile['body'])
            
            res = { 'idx':0, 'ret':1, 'msg':'ng', 'res':[] }
            if cityid != json_dict['cityid']:
                res['res'].append('this json file content dont match selected cityid.')
                self.write( json.dumps(res) )
                self.finish()
                return

            # update to mongodb
            data_card_info_mongo.update_city_card( cityid, json_dict['cards'] )
            
            res['msg'] = "update city's cards success. cityid:" + str(cityid)
            res['ret'] = 0
            self.write( json.dumps(res) )
            self.finish()
            return
        except Exception as e :
            log.exp(e)
            res = { 'idx':0, 'ret':1, 'msg':'ng', 'res':[] }
            self.write( json.dumps(res) )
            self.finish()
            return
 
        return self.redirect( r"/citycardupdate" )

'''
========================================
请注意：该行以下代码全部废弃
========================================
'''

'''
仅供后台使用，更新所有景点具体信息
path : sightinfoupdate
'''
class SightUpdateHandler(tornado.web.RequestHandler) :

    def get(self) :
        all_city = data_city_base_mysql.get_city_all_by_bg();
        city_sel = '选择城市<select onchange="" name="cityid">'
        for item in all_city :
            city_sel += '<option value="' + str(item['cityid']) + '">' + str(item['cname'])+ '</option>'
        city_sel += '</select><br /><br/>'
        
        self.write('''
                <html>
                <head><title>Upload City Map</title></head>
                <body>
                <form action='sightinfoupdate' enctype="multipart/form-data" method='post'>
                ''' 
                + city_sel +
                '''
                该城市所有景点信息的JSON文件<input type='file' name='jsonfile'/><br/><br/>
                <input type='submit' value='submit'/>
                </form>
                </body>
                </html>
            ''')

'''
    def post(self) :
        try :
            jsonfile = None
            try :
                jsonfile = self.request.files['jsonfile'][0]
            except Exception as e :
                print 'jsonfile need upload...'
            cityid = self.get_argument( 'cityid' )
        
            if not ( cityid and jsonfile ):
                log.w('params fetching error')
                res = { 'idx':0, 'ret':1, 'msg':'ng', 'res':[] }
                self.write( json.dumps(res) )
                self.finish()
                return
            
            jsonfile_res = file_util.map_file_upload(jsonfile, cityid)
            
            res = { 'idx':0, 'ret':1, 'msg':'ng', 'res':[] }
            if not jsonfile_res:
                res['res'].append('jsonfile upload failure.')
                log.e(res)
                self.write( json.dumps(res) )
                self.finish()
                return
        
            city_sights_dict = data_city_sights_mysql.get_city_sights_by_cityid( int (cityid) )
            log.i(city_sights_dict)
            
            sights_item = {}
            version = 1;
            if city_sights_dict:
                version += city_sights_dict['version']
        
            sights_item['cityid'] = int (cityid)
            sights_item['version'] = version
            sights_item['ctime'] = datetime.datetime.now()
            sights_item['jsonfile'] = 'http://static.shitouren.com/group'+str(jsonfile_res['group'])+'/'+jsonfile_res['path']+'.'+jsonfile_res['ext']
        
            update_res = data_city_sights_mysql.add_city_sights_item( sights_item )
            if not update_res :
                res['res'].append('add city map error. cityid=' + cityid)
                log.e(res)
                self.write( json.dumps(res) )
                self.finish()
                return
        
            update_res = data_city_base_mysql.update_city_version_by_cityid( int(cityid), p_versioninfo=version )
            if not update_res :
                res['res'].append('update city_base versioninfo error. cityid:' + cityid)
                log.e(res)
                self.write( json.dumps(res) )
                self.finish()
                return
        except Exception as e :
            log.exp(e)
            res = { 'idx':0, 'ret':1, 'msg':'ng', 'res':[] }
            self.write( json.dumps(res) )
            self.finish()
            return
 
        return self.redirect( conf.url['sightinfoupdate'] )
'''

      
'''
仅供后台使用，给城市的各景点导入图片
path : sightimginsert
'''
class SightImgInsertHandler(tornado.web.RequestHandler) :

    def get(self) :
        all_city = data_city_base_mysql.get_city_all_by_bg();
        city_sel = '选择城市<select onchange="" name="cityid">'
        for item in all_city :
            city_sel += '<option value="' + str(item['cityid']) + '">' + str(item['cname'])+ '</option>'
        city_sel += '</select><br />'
        
        sight_sel = '<br/>输入景点id<input type="text" name="sightid"/><br/>'
        img_index = '<br/>输入index<input type="text" name="img_index" value="1"/><br/>'
        self.write('''
                <html>
                <head><title>Upload Sight Image</title></head>
                <body>
                <form action='sightimginsert' enctype="multipart/form-data" method='post'>
                ''' 
                + city_sel + sight_sel + img_index +
                '''
                <input type='file' name='file'/><br/>
                <input type='file' name='file'/><br/>
                <input type='file' name='file'/><br/>
                <input type='file' name='file'/><br/>
                <input type='file' name='file'/><br/>
                <input type='file' name='file'/><br/>
                <input type='file' name='file'/><br/>
                <input type='file' name='file'/><br/>
                <input type='file' name='file'/><br/>
                <input type='file' name='file'/><br/>
                <input type='file' name='file'/><br/>
                <input type='file' name='file'/><br/>
                <input type='file' name='file'/><br/>
                <input type='file' name='file'/><br/>
                <input type='file' name='file'/><br/>
                <input type='file' name='file'/><br/>
                <input type='file' name='file'/><br/>
                <input type='file' name='file'/><br/>
                <input type='submit' value='submit'/>
                </form>
                </body>
                </html>
            ''')


    def post(self) :
        try :
            file_metas = self.request.files['file']
            img_index = int(self.get_argument( 'img_index' ))
            cityid = self.get_argument( 'cityid' )
            sightid = int( self.get_argument( 'sightid' ) )
        
            if not (cityid and sightid) :
                log.w('params fetching error')
                res = { 'idx':0, 'ret':0, 'msg':'ng', 'res':[] }
                self.write( json.dumps(res) )
                self.finish()
                return
        
            for meta in file_metas :
            
                # { "ret" : 0, "msg" : "ok", "res" : dst_res }
                res = file_util.img_file_upload(meta)
                if res['ret'] == 0 and res['res']:
                    dst_res = res['res']
                    item = {}
                    item['sightid']=int(sightid)
                    item['imgid']=dst_res['imgid']
                    item['index']=img_index
                    
                    data_sight_img_mysql.add_sight_img_item(int(cityid), item)
                    img_index += 1
        except Exception as e :
            log.exp(e)
            res = { 'idx':0, 'ret':1, 'msg':'ng', 'res':[] }
            self.write( json.dumps(res) )
            self.finish()
            return
 
        return self.redirect( conf.url['sightimginsert'] )

tcelery.setup_nonblocking_producer()
class AllUpdateHandler(tornado.web.RequestHandler):
    def get(self):
        all_city = data_city_base_mysql.get_city_all_by_bg()

        self.render('cms/city_update.html', city_info_list=all_city)

    @tornado.web.asynchronous
    def post(self):
        try:
            cityid = self.get_argument('city_id')

            update_all.apply_async(args=[cityid], callback=self.on_success)

        except Exception as e:
            log.exp(e)
            res = {'idx': 0, 'ret': 1, 'msg': 'ng', 'res': []}
            self.write(json.dumps(res))
            self.finish()
            return

    def on_success(self, response):
        # 获取返回的结果
        result = response.result
        self.write(json.dumps(result))
        self.finish()

class CityBaseAddHandler(tornado.web.RequestHandler):
    def format_bgcolor(self, color_str):
        color_len = len(color_str)
        if color_len == 6:
            return color_str + 'ff'
        elif color_len == 8:
            return color_str
        else:
            return False

    def post(self):
        try:
            cityid = self.get_argument('city_id', None)
            prov_id = self.get_argument('prov_id', None)
            name = self.get_argument('name', None)
            cname = self.get_argument('cname', None)
            pos_x = self.get_argument('pos_x', None)
            pos_y = self.get_argument('pos_y', None)
            version = self.get_argument('version', None)
            # versioninfo = self.get_argument('versioninfo')
            bgcolortop = self.get_argument('bgcolortop', None)
            bgcolorend = self.get_argument('bgcolorend', None)
            if not (cityid and prov_id and name and cname
                    and pos_x and pos_y
                    and version
                    and bgcolortop and bgcolorend):
                res = {'idx': 0, 'ret': 2, 'msg': '有字段为空，处理不了啊', 'res':[]}
                self.write(json.dumps(res))
                self.finish()
                return

            bgcolorend = self.format_bgcolor(bgcolorend)
            bgcolortop = self.format_bgcolor(bgcolortop)

            if not bgcolortop or not bgcolorend:
                res = {'idx': 0, 'ret': 4, 'msg': '颜色是8位', 'res': []}
                self.write(json.dumps(res))
                self.finish()
                return
            
            result = data_city_base_mysql.add_city_base_item({
                'cityid': cityid,
                'provid': prov_id,
                'name': name,
                'cname': cname,
                'pos_x': pos_x,
                'pos_y': pos_y,
                'version': version,
                # 'versioninfo': versioninfo,
                'bgcolortop': bgcolortop,
                'bgcolorend': bgcolorend,
            })

            if result:
                res = {'idx': 0, 'ret': 0, 'msg': '新建成功', 'res': []}
            else:
                res = {'idx': 0, 'ret': 3, 'msg': '新建失败', 'res': []}

            self.write(json.dumps(res))
            self.finish()
            return

        except Exception as e :
            log.exp(e)
            res = {'idx': 0, 'ret': 1, 'msg': 'ng', 'res': []}
            self.write(json.dumps(res))
            self.finish()
            return

class ApiNotFoundHandler( BaseHandler ) :

    def get( self ) :
        raise tornado.web.HTTPError( 503 )

    @tornado.web.asynchronous
    def post( self ) :
        log.i( '503' )
        res = { 'idx':-1, 'ret':-5, 'msg':etc.err_no_api, 'res':{} }
        self.write( json.dumps(res) )
        self.finish()


